package com.imay.live.fragment;

import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.imay.live.activity.ProfileActivity;
import com.imay.live.activity.RoomLiveNormalActivity;
import com.imay.live.activity.discovery.FollowControl;
import com.imay.live.activity.dynamics.SearchActivity;
import com.imay.live.adapter.SearchLinearAdapter;
import com.imay.live.analytics.MobclickAgent;
import com.imay.live.helper.EventHelper;
import com.imay.live.model.RoomInfoModel;
import com.imay.live.model.SearchResultModel;
import com.imay.live.model.UserModel;
import com.imay.live.proto.Result;
import com.imay.live.proto.ResultCode;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.view.custom.LoadRefreshViewControl;
import com.imay.live.view.recyclerview.WrapContentLinearLayoutManager;
import com.imay.live.R;
import com.imay.tbas_api.IMYTBASObject;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import java.util.ArrayList;

/**
 * Created by Administrator on 2017/05/03 0003.
 */

public class SearchUserFragment extends BaseRequestFragment {
    private RecyclerView mrecyclerView;
    private ArrayList<MultiItemEntity> mdatas;
    private SearchLinearAdapter mAdapter;
    private FrameLayout container;
    private LoadRefreshViewControl loadViewControl;
    private ArrayList<MultiItemEntity> suggestlist = new ArrayList<MultiItemEntity>();
    private String name;
    private FollowControl followControl;
    private IMYTBASObject mSocketNotify;
    private int count = 15;

    public static SearchUserFragment newInstance() {
        return new SearchUserFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.searchuser_layout;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        container = $(R.id.container);
        mdatas = new ArrayList<MultiItemEntity>();
        mAdapter = new SearchLinearAdapter(mdatas);
        loadViewControl = new LoadRefreshViewControl(getContext(), mAdapter, count);
        mrecyclerView = loadViewControl.addLoadView(container, new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                if (TextUtils.isEmpty(name)) {
                    refreshLoad();
                } else {
                    searchUser(name, true);
                }
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                if (TextUtils.isEmpty(name)) {
                } else {
                    moreLoad(mAdapter.getData().size(), name);
                }

            }
        }, false);
        loadViewControl.setError(getResources().getString(R.string.search_nouser));
        WrapContentLinearLayoutManager wrapContentLinearLayoutManager
                = new WrapContentLinearLayoutManager(getActivity());
        mrecyclerView.setLayoutManager(wrapContentLinearLayoutManager);
        mrecyclerView.setHasFixedSize(true);
        mrecyclerView.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {

                MobclickAgent.onEvent(getActivity(),"search_result_user");
                if (view.getId() == R.id.rl_left) {
                    SearchResultModel searchResultModel = (SearchResultModel) adapter.getItem(position);
                    if (searchResultModel.getUser() != null) {
                        ((SearchActivity) getActivity()).setDefault();
                        ProfileActivity.start(getActivity(), searchResultModel.getUser().getUid());
                    }
                } else if (view.getId() == R.id.search_right) {
                    SearchResultModel searchResultModel = (SearchResultModel) adapter.getItem(position);
                    gotoLive(searchResultModel);
                } else if (view.getId() == R.id.iv_add) {
                    SearchResultModel searchResultModel = (SearchResultModel) adapter.getItem(position);
                    if (searchResultModel != null) {
                        if (searchResultModel.getUser().isMyFollow()) {
                            gotoLive(searchResultModel);
                            return;
                        }
                        if (followControl == null) {
                            followControl = new FollowControl();
                        }
                        followControl.followChanged(getContext(), searchResultModel.getUser());
                    }
                }
            }
        });
        mrecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                ((SearchActivity) getActivity()).setDefault();
            }
        });
        mAdapter.bindToRecyclerView(mrecyclerView);
        refreshLoad();
        registerSocketNotify();
    }

    private void gotoLive(SearchResultModel searchResultModel) {
        ((SearchActivity) getActivity()).setDefault();
        if (searchResultModel.getUser() != null) {
            if (searchResultModel.getUser().getLiveStatus() == 1) {
                getRoonInfo(searchResultModel.getUser().getRoomId());
            } else {
                ProfileActivity.start(getActivity(), searchResultModel.getUser().getUid());
            }
        }
    }

    private void getRoonInfo(long roomId) {
        ProtoRequestHelper.task(ProtoHttpFactory.getRoomInfo(roomId)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                try {
                    Result<RoomInfoModel> result = JSON.parseObject(data, new TypeReference<Result<RoomInfoModel>>() {
                    }.getType());
                    if (result.result == ResultCode.CodeSuccess && result.data != null) {
                        RoomLiveNormalActivity.startActivity(getActivity(), result.data);
                    }

                } catch (Exception e) {
                    loadViewControl.setError(getResources().getString(R.string.search_nouser));
                }
            }

            @Override
            public void onRequestError(String command, int code, String message) {
                loadViewControl.setError(getResources().getString(R.string.search_nouser));
            }
        });
    }

    protected void registerSocketNotify() {
        mSocketNotify = new IMYTBASObject(false);
        mSocketNotify.stringCommand = EventHelper.EVENT_FOLLOW_UICHANGE;
        mSocketNotify.setDataResultListener(new IMYTBASObject.OnDataResultListener() {
            @Override
            public void onCommandTaskSuccess(final IMYTBASObject object) {
                String data = object.stringData;
                int sp = data.indexOf("#");
                if (sp > 0) {
                    String uid = data.substring(0, sp);
                    byUidSetChanged(Integer.valueOf(uid), false);
                } else {
                    byUidSetChanged(Integer.valueOf(data), true);
                }

            }
        });
        mSocketNotify.addEventListenWithTBASObject();
    }

    private void byUidSetChanged(int uid, final boolean follow) {
        if (mAdapter == null) {
            return;
        }
        ArrayList<MultiItemEntity> list = (ArrayList<MultiItemEntity>) mAdapter.getData();
        for (int i = 0; i < list.size(); i++) {
            Object multiItemEntity = list.get(i);
            if (multiItemEntity instanceof SearchResultModel) {
                SearchResultModel moreModel = (SearchResultModel) multiItemEntity;
                UserModel userModel = moreModel.getUser();
                if (userModel != null) {
                    if (userModel.getUid() == uid) {
                        userModel.setMyFollow(follow);
                        final int finalI = i;
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (followControl == null) {
                                    followControl = new FollowControl();
                                }
                                ImageView iv_add = (ImageView) followControl.getViewByPosition(mrecyclerView, finalI, R.id.iv_add);
                                if (iv_add == null) {
                                    mAdapter.notifyDataSetChanged();
                                } else {
                                    if (follow) {
                                        iv_add.setImageResource(R.mipmap.ico_00_jinru_btn);
                                    } else {
                                        iv_add.setImageResource(R.mipmap.btn_02phbguanzhu);
                                    }
                                }
                            }
                        });
                        break;
                    }
                }
            }
        }
    }

    private void refreshLoad() {
        loadViewControl.setEnableLoadmore(false);
        ProtoRequestHelper.task(ProtoHttpFactory.getsearchsuggestUserlList()).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {

                try {
                    Result<ArrayList<UserModel>> result = JSON.parseObject(data, new TypeReference<Result<ArrayList<UserModel>>>() {
                    }.getType());
                    suggestlist.clear();
                    if (result.result == ResultCode.CodeSuccess && result.data != null) {
                        for (UserModel user : result.data) {
                            SearchResultModel searchResultModel = new SearchResultModel();
                            searchResultModel.setUser(user);
                            suggestlist.add(searchResultModel);
                        }
                    }
                    loadViewControl.refreshLoadView(suggestlist, result.result);

                } catch (Exception e) {
                    loadViewControl.setError(getResources().getString(R.string.search_nouser));
                }
                loadViewControl.setEnableLoadmore(false);
            }

            @Override
            public void onRequestError(String command, int code, String message) {
                loadViewControl.setError(getResources().getString(R.string.search_nouser));
            }
        });

    }

    /**
     * @param name
     * @param isreset 是否刷新list
     */
    public void searchUser(String name, boolean isreset) {
        this.name = name;
        loadViewControl.setEnableLoadmore(true);
        refreshLoad(name, isreset);
    }

    private void moreLoad(int index, final String name) {
        ProtoRequestHelper.task(ProtoHttpFactory.getsearchuserList(index, name, count)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                try {
                    Result<ArrayList<UserModel>> result = JSON.parseObject(data, new TypeReference<Result<ArrayList<UserModel>>>() {
                    }.getType());
                    ArrayList<MultiItemEntity> list = new ArrayList<MultiItemEntity>();
                    if (result.result == ResultCode.CodeSuccess && result.data != null) {

                        for (UserModel user : result.data) {
                            SearchResultModel searchResultModel = new SearchResultModel();
                            searchResultModel.setUser(user);
                            list.add(searchResultModel);
                        }
                    }
                    loadViewControl.moreLoadView(list, result.result);


                } catch (Exception e) {
                    loadViewControl.setError(getResources().getString(R.string.search_nouser));
                }
            }

            @Override
            public void onRequestError(String command, int code, String message) {
                loadViewControl.setError(getResources().getString(R.string.search_nouser));
            }
        });
    }

    private void refreshLoad(final String name, final boolean isreset) {
        ProtoRequestHelper.task(ProtoHttpFactory.getsearchuserList(0, name, count)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                try {
                    Result<ArrayList<UserModel>> result = JSON.parseObject(data, new TypeReference<Result<ArrayList<UserModel>>>() {
                    }.getType());
                    ArrayList<MultiItemEntity> list = new ArrayList<MultiItemEntity>();
                    if (result.result == ResultCode.CodeSuccess && result.data != null) {
                        if (!isreset) {
                            ((SearchActivity) getActivity()).searchResult(result.data, name);
                        } else {
                            for (UserModel user : result.data) {
                                SearchResultModel searchResultModel = new SearchResultModel();
                                searchResultModel.setUser(user);
                                list.add(searchResultModel);
                            }
                        }
                    }
                    if (isreset) {
                        loadViewControl.refreshLoadView(list, result.result);
                    }


                } catch (Exception e) {
                    loadViewControl.setError(getResources().getString(R.string.search_nouser));
                }
            }

            @Override
            public void onRequestError(String command, int code, String message) {
                loadViewControl.setError(getResources().getString(R.string.search_nouser));
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mSocketNotify != null) {
            mSocketNotify.destroy();
        }
    }
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        // 友盟统计页面跳转，重写此方法，可以保证ViewPager切换Fragment时能够准确的记录Fragment之间的跳转
        // 不用再调用Fragment的生命周期方法
            if (isVisibleToUser) {
                MobclickAgent.onEvent(getActivity(),"search_user");
                MobclickAgent.onPageStart(getClass().getSimpleName());
            } else {
                MobclickAgent.onPageEnd(getClass().getSimpleName());
            }

    }
}
